<template>
  <div class="content flex-col">
    <div class="content_nav">
      <a-tabs v-model="activeName" @change="getList">
        <a-tab-pane v-for="item in categoryList" :key="item.index" :tab="item.title">
        </a-tab-pane>
        <template #tabBarExtraContent>
          <div class="content_buttons">
            <a-button type="primary" v-show="userAuthority.IMPORT" @click.stop="handleImport">
              <a-icon type="download" />
              导入
            </a-button>
            <a-button type="primary" v-show="userAuthority.ADD_APP" @click.stop="handleAdd">
              <a-icon type="plus" />
              添加场景
            </a-button>
            <a-radio-group v-model="displayModel" button-style="solid" style="margin-left: 10px">
              <a-radio-button value="card">卡片</a-radio-button>
              <a-radio-button value="list">列表</a-radio-button>
            </a-radio-group>
          </div>
        </template>
      </a-tabs>
    </div>
    <div v-if="displayModel === 'card'" class="content-card-list flex-row">
      <div class="content-card-item"
           v-for="(app, index) in appList"
           :key="app.id">
        <CgsCard :app-data="app"
                 :show-mask="app.appAuths.CONFIG_PROJECT"
                 @authority="handleAuthority(app, index)"
                 @delete-app="handleDeleteApp(app, index)"
                 @modify="handleModifyApp(app, index)"
                 @preview="handlePreview(app, index)"
                 @export-app="handleExport(app, index)"
                 @editor="handleEditorApp(app, index)"
        >
          <template slot="title">
            <a-tooltip>
              <template #title>{{app.title}}</template>
              {{app.title}}
            </a-tooltip>            
          </template>
        </CgsCard>
      </div>
    </div>
    <div v-if="displayModel === 'list'" class="content_list flex-col">
      <div class="content_list-item"
           style="width: 100%"
           v-for="(app, index) in appList"
           :key="app.id">
        <CgsList :app-data="app"
                 :show-mask="app.appAuths.CONFIG_PROJECT"
                 @authority="handleAuthority(app, index)"
                 @delete-app="handleDeleteApp(app, index)"
                 @modify="handleModifyApp(app, index)"
                 @preview="handlePreview(app, index)"
                 @export-app="handleExport(app, index)"
                 @editor="handleEditorApp(app, index)"
        >
          <template slot="title">
            {{app.title}}
          </template>
        </CgsList>
      </div>
    </div>
    <div class="content_floor">
      <el-pagination
          @size-change="pageSizeChange"
          @current-change="pageChange"
          :current-page="page.currentPage"
          :page-size="page.pageSize"
          :page-sizes="[12, 24, 36, 60, 120]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="page.total">
      </el-pagination>
    </div>

    <el-dialog :title="submitModel === 'add'? '一 添加场景 一': '一 修改信息 一'"
               :visible.sync="showAddScene"
               width="700px"
               center>
      <el-form label-position="left" label-width="120px"
               :model="formAddScene"
               :rules="formAddRules" ref="formAddScene"
      >
        <el-form-item label="组织:" prop="orgCategory">
          <el-select class="cgs-select"
                     v-model="formAddScene.orgCategory"
                     placeholder="选择组织"
          >
            <el-option v-for="category in orgCategoryList"
                       :key="category.index"
                       :value="category.index"
                       :label="category.title"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="分组:" prop="category">
          <el-select class="cgs-select"
                     v-model="formAddScene.category"
                     placeholder="选择分组"
          >
            <el-option v-for="category in categoryList"
                       :key="category.index"
                       :value="category.index"
                       :label="category.title"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="场景名称:" prop="title">
          <el-input class="cgs-input"
                    v-model="formAddScene.title"
                    placeholder="请输入场景名称"/>
        </el-form-item>
        <el-form-item label="密码:">
          <el-input class="cgs-input"
                    v-model="formAddScene.password"
                    placeholder="请输入密码"/>
        </el-form-item>
        <el-form-item label="发布状态:">
          <a-radio-group v-model="formAddScene.status" button-style="solid" style="margin-left: 10px">
            <a-radio-button value="release">发布</a-radio-button>
            <a-radio-button value="unrelease">未发布</a-radio-button>
          </a-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleSubmit">确 定</el-button>
        <el-button @click="showAddScene = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
  import CgsCard from "../components/CgsCard";
  import CgsList from "../components/CgsList";

  import {addObj, delObj, getCategory, getList, getObj, updateObj, uploadApp, uploadZip} from '@/api/visual';
  import {getTenantInfo, getUserAuthority, setUserAuthority} from "@/util/auth";
  import {getUserInfo} from "@/api/user";

  // import {url} from "@/config";
export default {
  name: "g3dmodel",
  components: {
    CgsList,
    CgsCard,
  },
  data(){
    return {
      userAuthority: {},
      page: {
        total: 0,
        pageSize: 12,
        currentPage: 1
      },
      categoryList: [],
      orgCategoryList: [],
      submitModel: "add",
      activeName: -1,
      formAddScene: {
        id: '',
        category: '',
        orgCategory: '',
        title: '',
        password: '',
        status: 'unrelease',
      },
      formAddRules: {
        category: [
          { required: true, message: '请选择分组', trigger: 'change' }
        ],
        title: [
          { required: true, message: '请输入场景名称', trigger: 'blur' }
        ],
      },
      displayModel: 'card',
      appList: [],
      showAddScene: false
    }
  },
  methods: {
    handleAdd () {
      this.submitModel = 'add';
      this.showAddScene = true
      this.formAddScene = {
        id: '',
        title: '',
        password: '',
        status: 'unrelease',
        orgCategory: '',
      }
      this.formAddScene.category = this.activeName
    },
    getList (category) {
      const loading = this.$loading({
        lock: true,
        text: '正在加载中，请稍后',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      this.appList = [];
      getList({
        Category: this.activeName,
        Current: this.page.currentPage,
        Size: this.page.pageSize,
        VisualType: this.visualType
      }).then(res => {
        loading.close();
        const data = res.data.data;
        this.page.total = data.total;
        let list = data.records;
        let appAuths = getUserAuthority().appAuths;

        for (let i = 0; i < list.length; i++) {
            if(this.visualType === 'App' || this.visualType === 'Workflow'){
                list[i]["backgroundUrl"] = "../img/bg/bg4.jpg"
            }
            list[i]["appAuths"] = {}
            if(appAuths[list[i].id]){
                for (let j = 0; j < appAuths[list[i].id].length; j++) {
                list[i]["appAuths"][appAuths[list[i].id][j]] = !this.tenantInfo.account.timeout;
                }
            }
        }
        // console.log(list);
        this.appList = list;
        // console.log(this.appList)
      })
    },
    handleImport() {
      let self = this;
      var inputObj = document.createElement('input')
      inputObj.setAttribute('id','importZip');
      inputObj.setAttribute('type','file');
      inputObj.setAttribute('name','importZip');
      inputObj.setAttribute("style",'visibility:hidden');
      document.body.appendChild(inputObj);
      inputObj.click();
      inputObj.addEventListener('change', e => {
        if(e.target.files[0]){
          const loading = this.$loading({
            lock: true,
            text: '正在导入，请稍后',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          });
          //创建formdata对象
          let formdata = new FormData();
          formdata.append("file", e.target.files[0]);

          formdata.append("category", self.activeName);

          if (self.visualType === 'App') {
            uploadApp(formdata).then(res => {
              if(res.data.code === 200){
                this.$message.success("导入成功！")
                this.updateAuthority();
              }else {
                this.$message.error("导入失败！")
              }
              loading.close();
            })
          } else {
            formdata.append("visualType", self.visualType);
            uploadZip(formdata).then(res => {
              if(res.data.code === 200){
                this.$message.success("导入成功！")
                this.updateAuthority();
              }else {
                this.$message.error("导入失败！")
              }
              loading.close();
            });
          }
        }
      });
    },
    handleSubmit() {
      this.$refs.formAddScene.validate((valid) => {
        if (valid) {
          let {status} = this.formAddScene
          status = status === 'release' ? 1: 0
          if (this.submitModel === 'add') {
            addObj(Object.assign(this.formAddScene, {
              status,
              isPortal: true,
              VisualType: this.visualType
            })).then(res => {
              if(res.data && res.data.success){
                this.updateAuthority();
                this.$message.success('添加成功');
              } else {
                this.$message.error('添加失败');
              }
              this.showAddScene = false
            })
          } else {
            updateObj(Object.assign(this.formAddScene, {
              status,
              isPortal: true,
              VisualType: this.visualType
            })).then(() => {
              this.showAddScene = false;
              this.$message.success('修改成功');
              this.getList(this.activeName);
            })
          }
        } else {
          return false;
        }
      });
    },
    handleAuthority(item) {
      this.$router.push({name: 'authority', params: {visualType: this.visualType, appId: item.id}})
    },
    handleDeleteApp(item, index) {
      this.$confirm('是否确认永久删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delObj({
          ID: item.id,
          VisualType: this.visualType
        }).then(() => {
          this.appList.splice(index, 1);
          this.$message.success('删除成功')
        })
      }).catch(() => {

      });
    },
    handleModifyApp(item) {
      this.submitModel = 'update';
      this.showAddScene = true;
      this.formAddScene.status = item.status === 1 ? 'release' : 'unrelease'
      this.formAddScene.category = item.category
      this.formAddScene.orgCategory = item.orgCategory
      this.formAddScene.title = item.title
      this.formAddScene.id = item.id
    },
    handlePreview(item) {
        if(this.visualType === 'App'){
            return
        }
        getObj({
            ID: item.id,
            VisualType: this.visualType
        }).then(res => {
            if (res.data.code === 200) {
            let config = res.data.data.config;
            var originHostName=window.location.hostname;
            // var protocol = window.location.protocol;
            var url= "";

            let visual = res.data.data.visual
              let port = '20000'
              switch(this.visualType){
                case 'Earth': port = '30000'
                  break;
                case 'TwoD': port = '40000'
                  break;
                case 'Bim': port = '45000'
                  break;
              }
            if (visual.projectID && visual.projectID !== "") {
                url = `//${originHostName}:${port}/viewer.html?ProjId=${visual.projectID}&mode=preview`
            } else if (config.sceneUrl && config.sceneUrl !== "") {
                // url=config.sceneUrl.replace(/\/\/.*:/,"//"+originHostName+":");// 替换IP
                url=config.sceneUrl;// cesium 临时使用
            }

              if("TwoD"==this.visualType) {
                url = `/2d/viewer.html?ProjId=${visual.projectID}&mode=preview`
              }else if("ThreeD" ==this.visualType){
                url = `/3d/viewer.html?ProjId=${visual.projectID}&mode=preview`
              }else if("Earth"==this.visualType){
                url = `/earth/viewer.html?ProjId=${visual.projectID}&mode=preview`
              }else if("Bim"==this.visualType){
                url = `/bim/viewer.html?ProjId=${visual.projectID}&mode=preview`
              }

            window.open(url, '_blank');
            }
        })
    },
    handleExport(item) {
      this.$confirm('确定导出', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        if(this.visualType === 'App'){
            let url = "/api/app/export?id=";
            // url = url.replace("localhost", window.location.hostname)
            window.open(url + item.id);
        } else{
            let url = "/api/Cgs/Portal/Export?visualId=";
            // url = url.replace("localhost", window.location.hostname)
            window.open(url + item.id + `&visualType=${this.visualType}`);
        }
      })
    },
    handleEditorApp(item) {
      console.log("open editor")
        const loading = this.$loading({
          lock: true,
          text: '正在打开，请稍后',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });
        if(this.visualType === 'App'){
            loading.close();
            this.$router.push({
                path: '/app/' + item.id
            })
        } else if(this.visualType === 'Workflow'){
            loading.close();
            let routeUrl = this.$router.resolve({
                path: '/workflow/' + item.id
            })
            window.open(routeUrl.href, '_blank');
        } else{
            getObj({
                ID: item.id,
                VisualType: this.visualType
            }).then(res => {
                if (res.data.code === 200) {
                    let config = res.data.data.config;
                    var originHostName=window.location.hostname;
                    var url= "";

                    let visual = res.data.data.visual;
                    let port = '20000'
                    switch(this.visualType){
                        case 'Earth': port = '30000'
                            break;
                        case 'TwoD': port = '40000'
                            break;
                        case 'Bim': port = '45000'
                            break;
                    }
                    if (visual.projectID && visual.projectID !== "") {
                        url = `//${originHostName}:${port}/viewer.html?ProjId=${visual.projectID}&mode=edit`
                    } else if (config.sceneUrl && config.sceneUrl !== "") {
                        url = config.sceneUrl;
                    }
                  // http://39.99.156.132:8888/?
                    if("TwoD"==this.visualType) {
                      url=`/2d/viewer.html?ProjId=${visual.projectID}&mode=edit`
                    }else if("ThreeD" ==this.visualType){
                      url = `/3d/viewer.html?ProjId=${visual.projectID}&mode=edit`
                    }else if("Earth"==this.visualType){
                      url = `/earth/viewer.html?ProjId=${visual.projectID}&mode=edit`
                    }else if("Bim"==this.visualType){
                      url = `/bim/viewer.html?ProjId=${visual.projectID}&mode=edit`
                    }



                    loading.close();
                    window.open(url, '_blank');
                }
            })
        }
    },
    pageSizeChange(value) {
      this.page.pageSize = value;
      this.getList(this.activeName);
    },
    pageChange(value) {
      this.page.currentPage = value;
      this.getList(this.activeName);
    },
    updateAuthority(){
      getUserInfo().then(infoRes => {
        if(infoRes.data && infoRes.data.success){
          setUserAuthority(infoRes.data.data);
          this.getList(this.activeName);
        }
      })
    },
    async init(){
        let categoryList = await getCategory({
            VisualType: this.visualType
        })
        let orgCategoryList = await getCategory({
            VisualType: 'Org'
        })
        this.orgCategoryList = orgCategoryList.map(d => {return {...d, ...{title: d.categoryKey, index: Number.parseInt(d.categoryValue)}}});
        // categoryKey
        this.categoryList = categoryList.map(d => {return {...d, ...{title: d.categoryKey, index: Number.parseInt(d.categoryValue)}}});
        // this.categoryList.unshift({title: '默认', index: 'default'})
        this.activeName = this.categoryList[0].index;
        this.formAddScene.category = this.categoryList[0].index;
        this.getList(this.activeName);

        let userAuth = getUserAuthority();
        this.tenantInfo = getTenantInfo();
        let authorities = userAuth["operatingAuthorities"];
        this.userAuthority = {};
        if(!authorities){
            authorities = [];
        }
        for (let i = 0; i < authorities.length; i++) {
            this.userAuthority[authorities[i]] = true;
        }
    }
  },
  computed:{
    visualType(){
        return this.$route.params.visualType
    }
  },
  watch: {
    $route(to, from) {
        this.init()
    }
  },
  created(){
      this.init()
  }
}
</script>
